import subprocess
import os
from Data.Chinese import model_number
from docx import Document

filepath = None
scg_cref = None
bianhao = None
filepath_all = None
filelist = None


# 分册编号
# 查找Title Page
def select_feiye():
    # noinspection PyGlobalUndefined
    global filepath
    flag = False
    # 获取所有文件路径
    file_paths = model_number.select_folder()
    # noinspection DuplicatedCode
    if file_paths == "-1":
        return "-1"
    # 如果有文件被选择
    if file_paths:
        # 遍历所有文件路径
        for file_path in file_paths:
            # 获取文件名
            file_name = os.path.basename(file_path)
            # 检查文件名是否包含"Title Page"
            if "Title Page" in file_name:
                filepath = file_path
                flag = True
                return file_path
    # 如果没有找到包含"Title Page"的文件，返回None
    if not flag:
        print("未找到Title Page")
        return "-1"


# 打开扉页，遍历内容
def open_feiye():
    global scg_cref
    arr_tool = []
    feiye_path = select_feiye()
    if feiye_path == "-1":
        return "-1"
    document = Document(feiye_path)
    content_array = []
    target_index = -1
    for index, paragraph in enumerate(document.paragraphs):
        if "Configuration" in paragraph.text:
            scg_cref = "配置指南"
            target_index = index + 1
            break
        if "Commands" in paragraph.text:
            target_index = index + 1
            scg_cref = "命令参考"
            break
    feiye = is_scg_cref()
    if feiye:
        for index, paragraph in enumerate(document.paragraphs[target_index:]):
            content_array.append(paragraph.text)
        for content in content_array:
            if "" == content:
                continue
            else:
                arr_tool.append(content)
        content_array = arr_tool
        # print(content_array)
    else:
        return "-1"
    return content_array


# 判断扉页是否属于命令或者配置
def is_scg_cref():
    global scg_cref
    global filepath
    # noinspection PyUnresolvedReferences
    path = (filepath.split('/')[-2])
    if scg_cref in path:
        return True
    else:
        print("扉页不符规范")


# 为模块进行编号
def sort():
    global bianhao
    global filelist
    # 获取扉页内容列表
    content_list = open_feiye()
    if content_list == "-1":
        return "-1"
    bianhao = content_list
    # for bh in bianhao:
    #     if "" == bh:
    #         continue
    #     else:
    #         bianhao_list.append(bh)
    # bianhao = bianhao_list
    # 创建新的编号后的列表
    numbered_list = []
    # 从1开始编号，使用enumerate获取索引
    for index, content in enumerate(content_list, 1):
        # 格式化序号为两位数（01, 02等）
        number = f"{index:02d}"
        # 拼接序号和内容
        numbered_content = f"{number}-{content}"
        numbered_list.append(numbered_content)
    filelist = numbered_list
    return numbered_list


# 拼接文件名
def filename():
    global scg_cref
    content_list = sort()
    if content_list == "-1":
        return "-1"
    numbered_list = []
    for text in content_list:
        text = f"{text}.docx"
        numbered_list.append(text)
    return numbered_list


# 文件重命名(不依赖SVN)
# noinspection PyTypeChecker
def rename():
    findname = []
    content_list = filename()
    if content_list == "-1":
        return "-1"
    global filepath_all, flag
    global bianhao
    global filepath
    global scg_cref
    filepath_all = model_number.filepath_all
    # noinspection PyUnresolvedReferences
    path = filepath.split('\\')[0]
    for oldfilename in filepath_all:
        old_path = oldfilename
        oldfilename = oldfilename.split('\\')[-1]
        oldfilename = oldfilename.rsplit('.', 1)[0]
        if "Title Page" in oldfilename:
            if "-" in oldfilename:
                continue
            else:
                feiye_name = f'00-{oldfilename}.docx'
                os.rename(old_path, f'{path}/{feiye_name}')
        if any(char.isdigit() for char in oldfilename) and "-" in oldfilename and oldfilename.split('-')[0].isdigit():
            oldfilename = '-'.join(oldfilename.split('-')[1:]).strip()
        for i, name in enumerate(bianhao):
            if name == oldfilename:
                newfilename = f"{path}/{content_list[i]}"
                # print(newfilename)
                try:
                    os.rename(old_path, newfilename)
                    findname.append(name)
                    flag = True
                except Exception as e:
                    flag = False
                    print(f"重命名失败:{e}")
    if flag:
        print("-------------------------")
        for feiye in bianhao:
            if feiye not in findname:
                print(f"扉页中文件缺失：{feiye}")
        print("-------------------------")
        for path in filepath_all:
            if "Title Page" in path:
                continue
            path = path.split('\\')[-1].rsplit('.', 1)[0]
            path = path.strip()
            if any(char.isdigit() for char in path) and "-" in path and path.split('-')[0].isdigit():
                actual_name = '-'.join(path.split('-')[1:]).strip()
                if actual_name not in findname and actual_name not in bianhao and "Title Page" not in path:
                    print(f"文件不在扉页中：{path}")
            else:
                if path not in findname and "~" not in path:
                    print(f"文件不在扉页中：{path}")
        print("-------------------------")
        print("程序执行完成！！！")
        # print("-------------------------")


def rename_svn():
    findname = []
    content_list = filename()
    if content_list == "-1":
        return "-1"
    global filepath_all, flag
    global bianhao
    global filepath
    global scg_cref
    filepath_all = model_number.filepath_all
    # noinspection PyUnresolvedReferences
    path = filepath.split('\\')[0]
    for oldfilename in filepath_all:
        old_path = oldfilename
        oldfilename = oldfilename.split('\\')[-1]
        oldfilename = oldfilename.rsplit('.', 1)[0]
        if "Title Page" in oldfilename:
            if "-" in oldfilename:
                continue
            else:
                feiye_name = f'00-{oldfilename}.docx'
                feiye_name = f'{path}/{feiye_name}'
                svn_command = f'svn mv "{old_path}" "{feiye_name}"'
                subprocess.run(svn_command, shell=True, check=True)
        if any(char.isdigit() for char in oldfilename) and "-" in oldfilename and oldfilename.split('-')[0].isdigit():
            oldfilename = '-'.join(oldfilename.split('-')[1:]).strip()
        # noinspection PyTypeChecker
        for i, name in enumerate(bianhao):
            if name == oldfilename:
                newfilename = f"{path}/{content_list[i]}"
                old_path = old_path.replace('\\', '/')
                try:
                    if old_path == newfilename:
                        findname.append(name)  # 即使跳过也要添加到 findname
                        flag = True
                        continue
                    else:
                        svn_command = f'svn mv "{old_path}" "{newfilename}"'
                        subprocess.run(svn_command, shell=True, check=True)
                        findname.append(name)
                        flag = True
                except subprocess.CalledProcessError as e:
                    print(f"SVN重命名失败: {e}")
                except Exception as e:
                    print(f"其它错误:{e}")
    if flag:
        print("-------------------------")
        # noinspection PyTypeChecker
        for feiye in bianhao:
            if feiye not in findname:
                print(f"扉页中文件缺失：{feiye}")
        print("-------------------------")
        for path in filepath_all:
            if "Title Page" in path:
                continue
            path = path.split('\\')[-1].rsplit('.', 1)[0]
            path = path.strip()
            if any(char.isdigit() for char in path) and "-" in path and path.split('-')[0].isdigit():
                actual_name = '-'.join(path.split('-')[1:]).strip()
                if actual_name not in findname and actual_name not in bianhao and "Title Page" not in path:
                    print(f"文件不在扉页中：{path}")
            else:
                if path not in findname and "~" not in path:
                    print(f"文件不在扉页中：{path}")
        print("-------------------------")
        print("程序执行完成！！！")
        # print("-------------------------")
